#include <QCoreApplication>
#include <QTimer>
#include <QDir>
#include <QFileInfo>
#include "quote_engine.h"
#include "quote_defines.h"
#include <QDebug>

Q_DECLARE_METATYPE(CThostFtdcDepthMarketDataField)

class QuoteDemo : public QObject
{
    Q_OBJECT
public:
    explicit QuoteDemo(QObject *parent = nullptr) 
        : QObject(parent), engine(new QuoteEngine::Engine(this))
    {
        // 连接信号
        connect(engine, &QuoteEngine::Engine::onStatusChanged, this, &QuoteDemo::handleConnectionStatus);
        connect(engine, &QuoteEngine::Engine::onError, this, &QuoteDemo::handleError);
        connect(engine, &QuoteEngine::Engine::onTick, this, &QuoteDemo::handleTick);
        
        // 设置定时器用于定期检查状态
        statusTimer = new QTimer(this);
        connect(statusTimer, &QTimer::timeout, this, &QuoteDemo::checkStatus);
        statusTimer->start(5000); // 每5秒检查一次
    }
    
    void start()
    {
        QuoteEngine::QuoteConfig config;
        // 设置行情配置
        //config.brokerID = "9999";
        //config.userID = "112537";
        //config.password = "zmin821001";
        //config.frontAddress = "tcp://180.168.146.187:10211";

        config.userID = "8641";
        config.password = "123456";  
        config.frontAddress = "tcp://openctp.cn:20004";
        config.flowPath = "/home/leexMarketLib/flow/";
        config.mdDllPath = "/home/leexMarketLib/include/CTP/thostmduserapi_tts.so";
        
        config.connection.enableUdp = false;
        config.connection.heartbeatTimeout = 15;
        
        config.log.path = "/home/leexMarketLib/logs/QuoteDemo";
        config.log.level = "debug";
        
        // 确保日志目录存在
        QDir().mkpath(QFileInfo(config.log.path).absolutePath());
        
        if (!engine->init(config)) {
            qDebug() << "Failed to initialize quote engine";
            QCoreApplication::quit();
            return;
        }
        
        // 启动行情引擎
        engine->start();
        qDebug() << "Quote engine started...";
    }
    
private slots:
    void handleConnectionStatus(QuoteEngine::ConnectionStatus status)
    {
        qDebug() << "Connection status changed:" 
                 << QuoteEngine::getConnectionStatusString(status);
        
        if (status == QuoteEngine::ConnectionStatus::Connected && !subscribed) {
            // 连接成功后订阅合约
            std::vector<QString> instruments = {"SA505", "ni2505", "m2505"};
            if (engine->subscribe(instruments)) {
                QStringList instrumentList;
                instrumentList.reserve(instruments.size());
                for (const auto& instrument : instruments) {
                    instrumentList << instrument;
                }
                qDebug() << "Successfully subscribed to:" << instrumentList;
                subscribed = true;
            } else {
                qDebug() << "Failed to subscribe to instruments";
            }
        }
    }
    
    void handleError(int errorCode, const QString& errorMsg)
    {
        qDebug() << "Error occurred:" << errorCode << errorMsg;
    }
    
    void handleTick(const CThostFtdcDepthMarketDataField& data)
    {
        count++;
    }
    
    void checkStatus()
    {
        if (engine) {
            qDebug() << "Connection status:" 
                     << QuoteEngine::getConnectionStatusString(engine->connectionStatus())
                     << "count:" << count;
        }
    }

private:
    QuoteEngine::Engine* engine;
    QTimer* statusTimer;
    bool subscribed{false};
    int count{0};
};

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);
    
    // 注册自定义类型
    qRegisterMetaType<CThostFtdcDepthMarketDataField>("CThostFtdcDepthMarketDataField");
    
    QuoteDemo demo;
    demo.start();
    
    return app.exec();
}

#include "quote_demo.moc" 